/*global $*/
const getYearMonthString = (year, month) => {
    return `${year}-${month / 10 >= 1 ? month : `0${month}`}`;
};

const parseYearMonthString = (yearMonthString) => {
    let year = parseInt(yearMonthString.slice(0, 4), 10);
    let month = parseInt(yearMonthString.slice(5, 7), 10);
    return {
        year: year,
        month: month
    }
}

const getDayListObjOfMonth = (year, month) => {
    // debugger;
    let first = new Date(year, month - 1, 1);
    let offsetDay = first.getDay();
    let daysOfMonth = (new Date(year, month, 0)).getDate();
    let dateList = [];
    let dayListObjName = `${year}-${month / 10 >= 1 ? month : `0${month}`}`;
    let dayListObjOfMonth = {};

    for(let i = 0; i < offsetDay; i++) {
        dateList.push(0);
    }

    for(let j = 1; j <= daysOfMonth; j++) {
        dateList.push(j);
    }

    // dayListObjOfMonth.set(dayListObjName, dateList);
    dayListObjOfMonth[dayListObjName] = dateList;

    return dayListObjOfMonth;
};

const constructWorkouts = (rawWorkouts) => {
    let workouts = {};

    if(rawWorkouts.length) {
    let count = 0; // count the uncompleted workout number

    rawWorkouts.forEach(item => {
        let lastUpdate = item.pivot.updated_at;
        let lastUpdateMonth = lastUpdate.slice(0, 7);
        let lastUpdateDate = parseInt(lastUpdate.slice(8, 10), 10);

        if(item.pivot.is_complete) {
            workouts[lastUpdateMonth] = workouts[lastUpdateMonth] || {};
            workouts[lastUpdateMonth][lastUpdateDate] = item;
        } else {
            let currDay = new Date();
            let putDay = new Date(currDay.getFullYear(), currDay.getMonth(), currDay.getDate() + count);
            let putYearMonth = getYearMonthString(putDay.getFullYear(), putDay.getMonth() + 1);

            workouts[putYearMonth] = workouts[putYearMonth] || {};
            workouts[putYearMonth][putDay.getDate()] = item;

            count++;
        }
    });
    }

    return workouts;
}

export default {
    getYearMonthString,
    parseYearMonthString,
    getDayListObjOfMonth,
    constructWorkouts
}
